<?php
defined('is_running') or die('Not an entry point...');

function readData($filename) {
  $fh = fopen($filename, 'r');
  if(!$fh) exit("unable to open file ($filename)");

  while (!feof($fh))
    $lines[] = trim(fgets($fh));
  fclose($fh);
  unset($lines[count($lines) - 1]); // remove last \n

  return $lines;
}

function writeData($file_data, $lines, $attr) {
  $fh = fopen($file_data, $attr);
  foreach($lines as $line)
    fwrite($fh, $line."\n");
  fclose($fh);
}

function addFavourites($fav_name, $fav_url, $fav_cat, $fav_date) {
  //global $fav_data;
  $fav_data = "data/_pages/plugins/data/fav.txt";

  $lines = readData($fav_data);

  if (count($lines) > 0) { // if file is not empty
    list($last_fav_id) = explode("|", $lines[count($lines) - 1]); // take last $fav_id
    $new_fav_id = $last_fav_id + 1;
  } else {
    $new_fav_id = 0;
  }
  
  $last_line[] = "$new_fav_id|$fav_name|$fav_url|$fav_cat|$fav_date";
  writeData($fav_data, $last_line, 'a');
}

function delFavourites($fav_id) {
//  global $fav_data;
  $fav_data = "data/_pages/plugins/data/fav.txt";
  $lines = readData($fav_data);

  for ($i = 0; $i < count($lines); $i++) {
    list($delrow) = explode("|", $lines[$i]);

    if (strcmp($delrow, $fav_id) == 0)
      $unset_i = $i;
  }
  unset($lines[$unset_i]);

  writeData($fav_data, $lines, 'w');
}

function addCategories($cat_name) {
//  global $cat_data;
  $cat_data = "data/_pages/plugins/data/cat.txt";
  $lines = readData($cat_data);

  if (count($lines) > 0) { // if file is not empty
    list($last_cat_id) = explode("|", $lines[count($lines) - 1]); // take last $cat_id
    $new_cat_id = $last_cat_id + 1;
  } else {
    $new_cat_id = 0;
  }

  $last_line[] = "$new_cat_id|$cat_name";
  writeData($cat_data, $last_line, 'a');
}

function delCategories($cat_id) {
//  global $cat_data;
  $cat_data = "data/_pages/plugins/data/cat.txt";
  $lines = readData($cat_data);

  for ($i = 0; $i < count($lines); $i++) {
    list($delrow) = explode("|", $lines[$i]);

    if (strcmp($delrow, $cat_id) == 0)
      $unset_i = $i;
  }
  unset($lines[$unset_i]);

  writeData($cat_data, $lines, 'w');
}
?>
